#PBAR_Zspec_MarToCSV.py

import os
import sys
import csv
#from sys import argv

def ConvertMarToDice(arg):
    """Converts mar file to dice by running dice Z-spec-136.cut
        If only one argument, then will assume that you have provided the full file name for one file
        If more than one argument provided, then it assumes that you have provided
        the file name prefix ("dz", "ea", etc), the directory where the files are located, the first dataset number, 
        the second dataset number, 
    """
    diceScriptName = 'Z-spec-136.cut'
    script, prefix, fileLocation, datasetNumFirst, datasetNumLast = arg
    filenameList = []
    for i in xrange(int(datasetNumFirst), int(datasetNumLast)+1):
        filenameList.append(prefix + '%02d' % i)
#        fullFilenameList.append(os.path.join(fileLocation, prefix + '%02d' % i))
    
    # Cycle through the list of files
    for (index, filename) in enumerate(filenameList):
        print('Running: dice %s %s .' %(diceScriptName, filename))
        os.system('dice %s %s .' %(diceScriptName, filename))
    print('Done.')

def ConvertDiceToCSV(arg):
    """Converts Dice Zspec file to CSV"""    
    script, prefix, fileLocation, datasetNumFirst, datasetNumLast = arg

    filenameList = []
    for i in xrange(int(datasetNumFirst), int(datasetNumLast)+1):
        filenameList.append(prefix + '%02d.txt' % i)
    
    # Cycle through the list of files
    for (index, filename) in enumerate(filenameList):
        # Read in csv file
        print os.path.join(fileLocation, filename)
        fid = open(os.path.join(fileLocation, filename), 'rb')
        csvReaderObj = csv.reader(fid, delimiter = ',')

        countAll = []
        for d in xrange(136):
            count = []
            print d
            # skip first line
            temp = csvReaderObj.next()
            for i in xrange(256):
                temp = csvReaderObj.next()
                count.append(temp[1]) # append the count array
            # skip last line
            temp = csvReaderObj.next()
            countAll.append(count)
        fid.close()
        
        # open file for writing        
        fid = open(os.path.join(fileLocation, filename.replace('.txt', '.csv')), 'wb')
        csvWriterObj = csv.writer(fid)
        # write first line - "","D1", "D2"
        lineOut = []
        lineOut.append(" ")
        for d in xrange(136):
            lineOut.append("D%d" %(d+1))
        csvWriterObj.writerow(lineOut)
        # write the data
        for i in xrange(256):
            lineOut = []
            lineOut.append(i)
            for d in xrange(136):
                lineOut.append(countAll[d][i])
            csvWriterObj.writerow(lineOut)
        fid.close()
        
    print('Done.')

if __name__ == "__main__":
#    ConvertMarToDice(sys.argv)
    ConvertDiceToCSV(sys.argv)
    
